package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.dto.PostDTO;
import com.example.demo.mapper.PostMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.po.Post;
import com.example.demo.entity.po.User;
import com.example.demo.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<PostDTO> getHotPosts(Integer page, Integer size) {
        // 1. 分页查询帖子
        Page<Post> postPage = postMapper.selectPage(
            new Page<>(page, size),
            new LambdaQueryWrapper<Post>()
                .orderByDesc(Post::getCreatedAt)
        );


        if (postPage.getRecords().isEmpty()) {
            return new Page<PostDTO>().setRecords(Collections.emptyList());
        }

        // 2. 获取所有发帖用户的ID
        Set<Long> userIds = postPage.getRecords().stream()
            .map(Post::getUserId)
            .collect(Collectors.toSet());

        // 3. 批量查询用户信息
        List<User> users = userMapper.selectList(
            new LambdaQueryWrapper<User>()
                .in(User::getUserId, userIds)
        );
        Map<Long, User> userMap = users.stream()
            .collect(Collectors.toMap(User::getUserId, user -> user));

        // 4. 转换为DTO
        List<PostDTO> dtoList = postPage.getRecords().stream().map(post -> {
            PostDTO dto = new PostDTO();
            dto.setPostId(post.getPostId());
            dto.setUserId(post.getUserId());
            
            // 设置用户信息
            User user = userMap.get(post.getUserId());
            if (user != null) {
                dto.setNickname(user.getNickname());
                dto.setAvatar(user.getAvatar());
            }
            
            dto.setContent(post.getContent());
            // 处理媒体URL
            if (post.getMediaUrl() != null) {
                dto.setMediaUrls(Arrays.asList(post.getMediaUrl().split(",")));
            }
            dto.setLocation(post.getLocation());
            dto.setCreatedAt(post.getCreatedAt());
            
            // 计算发布时间
            dto.setTimeAgo(calculateTimeAgo(post.getCreatedAt()));
            
            return dto;
        }).collect(Collectors.toList());

        // 5. 返回分页结果
        Page<PostDTO> dtoPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }

    private String calculateTimeAgo(LocalDateTime dateTime) {
        LocalDateTime now = LocalDateTime.now();
        long minutes = ChronoUnit.MINUTES.between(dateTime, now);
        
        if (minutes < 60) {
            return minutes + "分钟前";
        }
        
        long hours = ChronoUnit.HOURS.between(dateTime, now);
        if (hours < 24) {
            return hours + "小时前";
        }
        
        long days = ChronoUnit.DAYS.between(dateTime, now);
        if (days < 30) {
            return days + "天前";
        }
        
        long months = ChronoUnit.MONTHS.between(dateTime, now);
        if (months < 12) {
            return months + "个月前";
        }
        
        return ChronoUnit.YEARS.between(dateTime, now) + "年前";
    }
} 